package com.hrb.monkey.frament;


import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.commonsdk.okhttp.listener.DisposeDownloadListener;
import com.hrb.monkey.CustomApplication;
import com.hrb.monkey.R;
import com.hrb.monkey.UserAdapter;
import com.hrb.monkey.constant.Constant;
import com.hrb.monkey.network.http.RequestCenter;
import com.hrb.monkey.record.FirsFragmentRecord;
import com.hrb.monkey.record.User;
import com.hrb.monkey.record.bilicontentRecod;
import com.hrb.monkey.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * A simple {@link Fragment} subclass.
 */
@RuntimePermissions
public class ThirdFragment extends Fragment implements View.OnClickListener {


    @BindView(R.id.qrcode_view)
    TextView qrcodeView;
    @BindView(R.id.category_view)
    TextView categoryView;
    @BindView(R.id.search_view)
    TextView searchView;
    @BindView(R.id.loading_view)
    ImageView loadingView;
    @BindView(R.id.list_view)
    RecyclerView listView;
    Unbinder unbinder;
    @BindView(R.id.swipe_refresh)
    SmartRefreshLayout swipeRefresh;
    @BindView(R.id.third_title_bar)
    RelativeLayout thirdTitleBar;
    private int scrollY = 0;
    private List<User> flist;
    private NotificationManager notificationManager;
    private NotificationCompat.Builder builder;
    private Notification notification;

    public ThirdFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_third, container, false);
        unbinder = ButterKnife.bind(this, view);
        categoryView.setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listView.setLayoutManager(layoutManager);
        flist = new ArrayList<>();
        listView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("messageDY : ", dy + "");
                scrollY += dy;
                if (scrollY > 100) {
                    thirdTitleBar.setVisibility(View.GONE);
                }else{
                    thirdTitleBar.setVisibility(View.VISIBLE);
                }
                Log.d("message : ", scrollY + "");
            }
        });

        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                requestData();
                //new LoadInfoGson(recyclerView, linearLayoutManager).execute("https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/userInfo");
                swipeRefresh.finishLoadMore(2000);
            }
        });
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestData();
        //初始化通知
        initNotification();

    }


    private void requestData() {
        RequestCenter.requestRecommandData(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                FirsFragmentRecord user = (FirsFragmentRecord) responseObj;
                if (user != null && user.data.size() > 0) {
                    loadingView.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);
                    flist.addAll(user.data);
                    UserAdapter madpter = new UserAdapter(flist);
                    listView.setAdapter(madpter);
                }
            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        });
        //applyPermissions();
        ThirdFragmentPermissionsDispatcher.applyPermissionsWithPermissionCheck(this);
    }


    //初始化通知
    private void initNotification() {
        notificationManager = (NotificationManager)CustomApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(CustomApplication.getContext());
        builder.setContentTitle("正在更新...") //设置通知标题
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setLargeIcon(BitmapFactory.decodeResource(CustomApplication.getContext().getResources(), R.mipmap.ic_launcher_round)) //设置通知的大图标
                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
                .setAutoCancel(false)//设置通知被点击一次是否自动取消
                .setContentText("下载进度:" + "0%").setAutoCancel(true)
                .setProgress(100, 0, false);
                 notification = builder.build();//构建通知对象

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void applyPermissions() {
        RequestCenter.downloadFile("http://m10.music.126.net/20190408115739/94158f249eb40d02eaa34efba4e7e666/ymusic/5dcc/08da/a75e/09e8c111ce449b2c0a1b5e999b792645.mp3", Constant.APP_MUSIC_DIR + "79889293185cedac93b5c3e622fa1bd7.mp3", new DisposeDownloadListener() {
            @Override
            public void onProgress(int progrss) {
                Log.d("dddd :", progrss + "");
                builder.setProgress(100,progrss,false);
                builder.setContentText("现在进度:"+progrss+"%");
                notification=builder.build();
                notificationManager.notify(1,notification);
            }

            @Override
            public void onSuccess(Object responseObj) {
                String temp = responseObj.toString();
                ToastUtil.show(temp.substring(temp.lastIndexOf("/") + 1, temp.length()));
                /*builder.setContentTitle("下载完成")
                        .setContentText("点击安装")
                        .setAutoCancel(true);
                //设置通知被点击一次是否自动取消
        //点击安装代码块
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
                PendingIntent pi = PendingIntent.getActivity(getContext(), 0, intent, 0);
                notification = builder.setContentIntent(pi).build();
                notificationManager.notify(1, notification);*/
            }

            @Override
            public void onFailure(Object reasonObj) {
                ToastUtil.show(reasonObj.toString());
            }
        });
    }

    private void postmessage() {

        RequestCenter.postRequest("https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/bilicontent", null, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                bilicontentRecod bilicontentRecod = (com.hrb.monkey.record.bilicontentRecod) responseObj;
                ToastUtil.show(bilicontentRecod.toString());


            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        }, bilicontentRecod.class);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ThirdFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.category_view:
                postmessage();
                break;

        }

    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForContact(final PermissionRequest request) {
        new AlertDialog.Builder(CustomApplication.getContext())
                .setMessage("使用此功能需要WRITE_EXTERNAL_STORAGE和RECORD_AUDIO权限，下一步将继续请求权限")
                .setPositiveButton("下一步", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();//继续执行请求
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.cancel();//取消执行请求
            }
        }).show();
    }

}
